package com.ahu.qifei.fund.service.impl;

import com.ahu.qifei.fund.bean.ResultModel;
import com.ahu.qifei.fund.common.enums.ResultEnum;
import com.ahu.qifei.fund.common.util.Assert;
import com.ahu.qifei.fund.entity.Fund;
import com.ahu.qifei.fund.mapper.FundMapper;
import com.ahu.qifei.fund.service.IFundService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ShiQifei
 * @since 2020-11-20
 */
@Service
public class FundServiceImpl extends ServiceImpl<FundMapper, Fund> implements IFundService {
    private final static String JQUERY_JSONP = "jQuery18307947671564988703_1605771974498";
    private final static String FUND_URL = "http://api.fund.eastmoney.com/f10/lsjz?pageIndex=1&pageSize=200";
    // 源
    private final static String FUND_REFERER = "http://fundf10.eastmoney.com/";
    @Autowired
    RestTemplate restTemplate;
    /**
     * 查询基金的详情
     *
     * @param fundCode
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public ResultModel detail(String fundCode, String startDate, String endDate) {
        Date todayDate = new Date();
        StringBuffer url = new StringBuffer(FUND_URL);
        url.append("&").append("fundCode=").append(fundCode).
                append("&").append("startDate=").append(startDate).
                append("&").append("endDate=").append(endDate).
                append("&").append("callback=").append(JQUERY_JSONP).
                append("&").append("_=").append(todayDate.getTime());

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Referer", FUND_REFERER);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, httpHeaders);
        ResponseEntity<String> result = restTemplate.exchange(url.toString(), HttpMethod.GET,requestEntity,String.class);
        JSONArray fundObject = null;
        if(result != null && result.getStatusCodeValue() == HttpStatus.OK.value()) {
            String body = result.getBody();
            Assert.notNull(body, ResultEnum.INVALID_PARAM);
            String tempJSONP = body.replace(JQUERY_JSONP, "").substring(1);
            JSONObject jsonObject = JSON.parseObject(tempJSONP.substring(0, tempJSONP.length() -1));
            fundObject = jsonObject.getJSONObject("Data").getJSONArray("LSJZList");
        }
        Collections.reverse(fundObject);
        return ResultModel.success(fundObject);
    }
}
